package com.vipheyue.bigbusiness.activity;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.bmob.BTPFileResponse;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadListener;
import com.google.gson.Gson;
import com.lidroid.xutils.util.LogUtils;
import com.vipheyue.bigbusiness.R;
import com.vipheyue.bigbusiness.bean.Company;
import com.vipheyue.bigbusiness.bean.Job;
import com.vipheyue.bigbusiness.utils.UriConfig;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

public class UploadDataActivity extends AppCompatActivity {


    @Bind(R.id.iv_image)
    ImageView iv_image;
    @Bind(R.id.iv_image2)
    ImageView iv_image2;
    private ArrayList<BmobFile> imageList;
    private Job job;
    private String path2;
    private String ram = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_data);
        ButterKnife.bind(this);
        Bitmap image = ((BitmapDrawable) iv_image.getDrawable()).getBitmap();
        Bitmap image2 = ((BitmapDrawable) iv_image2.getDrawable()).getBitmap();
        String path = saveToSdCard(image, ram + "path");
        path2 = saveToSdCard(image2, ram + "heyue");
        upDateNewCompany(path2);
//        upDateCompany(path);
//    createNewCompany();
//        for (int i = 0; i < 40; i++) {
//            createNewObj(path);
//        }
//        queryJob();
    }

    private void upDateNewCompany(String filePath) {

        BTPFileResponse response = BmobProFile.getInstance(this).upload(filePath, new UploadListener() {

            @Override
            public void onSuccess(String fileName, String url, BmobFile file) {
                Log.i("bmob", "文件上传成功：" + fileName + ",可访问的文件地址：" + file.getUrl());
                // TODO Auto-generated method stub
                // fileName ：文件名（带后缀），这个文件名是唯一的，开发者需要记录下该文件名，方便后续下载或者进行缩略图的处理
                // url        ：文件地址
                // file        :BmobFile文件类型，`V3.4.1版本`开始提供，用于兼容新旧文件服务。
                //    注：若上传的是图片，url地址并不能直接在浏览器查看（会出现404错误），需要经过`URL签名`得到真正的可访问的URL地址,当然，`V3.4.1`的版本可直接从'file.getUrl()'中获得可访问的文件地址。
                /***************************************/
                Company company = new Company();
                company.setContactsPeople("张泽瀛");
                company.setContactsPhone("18584500432");
                company.setCompanyLogo(file);
                company.update(UploadDataActivity.this, UriConfig.releaseCompanyId, new UpdateListener() {

                    @Override
                    public void onSuccess() {
                        // TODO Auto-generated method stub
                        Log.i("bmob", "更新成功：");
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        // TODO Auto-generated method stub
                        Log.i("bmob", "更新失败：" + msg);
                    }
                });
/***************************************/
            }

            @Override
            public void onProgress(int progress) {
                // TODO Auto-generated method stub
                Log.i("bmob", "onProgress :" + progress);
            }

            @Override
            public void onError(int statuscode, String errormsg) {
                // TODO Auto-generated method stub
                Log.i("bmob", "文件上传失败：" + errormsg);
            }
        });

    }

    private void upDateCompany(String path) {


        final BmobFile bmobFile = new BmobFile(new File(path));
        bmobFile.upload(this, new UploadFileListener() {
            @Override
            public void onSuccess() {
/***************************************/
                Company company = new Company();
                company.setContactsPeople("张泽瀛");
                company.setContactsPhone("18584500434");
                company.setCompanyLogo(bmobFile);
                company.update(UploadDataActivity.this, "7847c8c44a", new UpdateListener() {

                    @Override
                    public void onSuccess() {
                        // TODO Auto-generated method stub
                        Log.i("bmob", "更新成功：");
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        // TODO Auto-generated method stub
                        Log.i("bmob", "更新失败：" + msg);
                    }
                });
/***************************************/
            }

            @Override
            public void onFailure(int i, String s) {

            }
        });


    }

    private void queryJob() {
        BmobQuery<Job> query = new BmobQuery<Job>();
        query.addWhereEqualTo("objectId", "f998985af9");    // 查询当前用户的所有帖子
        query.include("publisherCompany");// 希望在查询帖子信息的同时也把发布人的信息查询出来
        query.findObjects(this, new FindListener<Job>() {
            @Override
            public void onSuccess(List<Job> object) {
                // TODO Auto-generated method stub
                Job job = object.get(0);
                Gson gson = new Gson();
                LogUtils.i(gson.toJson(job));

                Company company = job.getPublisherCompany();
                LogUtils.i(gson.toJson(company));
            }

            @Override
            public void onError(int code, String msg) {
                // TODO Auto-generated method stub
            }
        });
    }

    private void createNewCompany() {
        Company company = new Company();
        company.setCompanyAddress("重庆石桥铺");
        company.setCompanyDescription("公司具有...公司描述");
        company.setCompanyName("重庆酷牛科技");
        company.setPublisherLevel(1);
        company.save(this, new SaveListener() {

            @Override
            public void onSuccess() {
                Toast.makeText(UploadDataActivity.this, "上传成功", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(int code, String arg0) {
                Toast.makeText(UploadDataActivity.this, "上传失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    public String saveToSdCard(Bitmap bitmap, String ram) {
        String files = getCacheDir() + ram + "zzzzsdsdsds3_12.jpg";

        File file = new File(files);
        try {
            FileOutputStream out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
                out.flush();
                out.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        LogUtils.i(file.getAbsolutePath());
        return file.getAbsolutePath();
    }
/*
废弃
 */
    private void createNewObj(final String path) {
        job = new Job();
        Company company = new Company();
        company.setObjectId("7847c8c44a");
        job.setPublisherCompany(company);
        job.setJobTitle("Android程序员");
        job.setJobType("实习");
        job.setPartTimeJob(true);
        job.setWorkAreaType("重庆");
        job.setWorkAddressDetail("重庆九龙坡石桥铺协和医院");
        job.setContactAddress("广州-佛山");
        job.setEducationLevel("本科");
        job.setMinSalary("5000");
        job.setMaxSalary("8000");
        job.setWorkDay("周末");
        job.setContactsPhone("18584500435");
        job.setDetailDescription("任职资格相关专业本科或以上学历");
        imageList = new ArrayList<BmobFile>();
        final BmobFile bmobFile = new BmobFile(new File(path));
        imageList.add(bmobFile);
        job.setJobImageList(imageList);

        bmobFile.upload(this, new UploadFileListener() {
            @Override
            public void onSuccess() {
                imageList.add(bmobFile);
                upDateNext(path);
            }

            @Override
            public void onFailure(int i, String s) {

            }
        });


    }

    private void upDateNext(final String path) {
        final BmobFile bmobFile = new BmobFile(new File(path2));
        bmobFile.upload(this, new UploadFileListener() {
            @Override
            public void onSuccess() {
                imageList.add(bmobFile);
                job.save(UploadDataActivity.this, new SaveListener() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(UploadDataActivity.this, "上传成功", Toast.LENGTH_LONG).show();
                        LogUtils.i("上传成功");
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        Toast.makeText(UploadDataActivity.this, "上传失败" + s, Toast.LENGTH_LONG).show();
                        LogUtils.i("上传失败" + s);

                    }
                });
            }

            @Override
            public void onFailure(int i, String s) {

            }
        });
    }

}
